package com.htgd.gardenexpo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.*;
import com.htgd.gardenexpo.dto.GeConTheaterMovieDTO;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.page.MovieQuery;
import com.htgd.gardenexpo.service.GeBaseDictService;
import com.htgd.gardenexpo.service.GeConTheaterMovieService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htgd.gardenexpo.service.GeConTheaterPlanService;
import com.htgd.gardenexpo.utils.TokenUtil;
import com.htgd.gardenexpo.vo.GeConTheaterMovieVO;
import com.htgd.gardenexpo.vo.TheaterList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 剧场资源 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-09-02
 */
@Service
public class GeConTheaterMovieServiceImpl extends ServiceImpl<GeConTheaterMovieMapper, GeConTheaterMovie> implements GeConTheaterMovieService {

    @Autowired
    private GeConTheaterMovieMapper geConTheaterMovieMapper;

    @Autowired
    private GeBaseDictService geBaseDictService;

    @Autowired
    private GeConTheaterPlanMovieMapper geConTheaterPlanMovieMapper;

    @Autowired
    private GeConTheaterSeatTimeMapper geConTheaterSeatTimeMapper;

    @Autowired
    private GeConTheaterSeatMapper geConTheaterSeatMapper;

    @Autowired
    private GeConTheaterMovieActorMapper geConTheaterMovieActorMapper;

    @Autowired
    private GeConTheaterPlanMapper geConTheaterPlanMapper;


    @Override
    public PageInfo<GeConTheaterMovieVO> pageList(MovieQuery movieQuery) {
        PageHelper.startPage(movieQuery.getPageNum(), movieQuery.getPageSize());
        List<GeConTheaterMovieVO> list= geConTheaterMovieMapper.pageList(movieQuery);
        for (GeConTheaterMovieVO geConTheaterMovieVO : list) {
            if(geConTheaterMovieVO.getStatus()!=null){
                geConTheaterMovieVO.setStatusText(geBaseDictService.getStatusText(String.valueOf(geConTheaterMovieVO.getStatus())));
            }

            if(geConTheaterMovieVO.getIsTop()!=null){
                geConTheaterMovieVO.setIsTopText(geBaseDictService.getTopText(String.valueOf(geConTheaterMovieVO.getIsTop())));
            }

            //类型字典
            if(geConTheaterMovieVO.getType()!=null){
                String typeText = "";
                String[] split = geConTheaterMovieVO.getType().split(",");
                for (String s : split) {
                    String type_movie = geBaseDictService.getTextByCodeAndValue("type_movie", s);
                    typeText = typeText + type_movie+"/";

                }
                geConTheaterMovieVO.setTypeText(typeText.substring(0,typeText.length()-1));
            }

            List<GeConTheaterMovieActor> geConTheaterMovieActors = geConTheaterMovieActorMapper.selectList(new LambdaQueryWrapper<GeConTheaterMovieActor>().eq(GeConTheaterMovieActor::getMovieId, geConTheaterMovieVO.getId()));
            geConTheaterMovieVO.setActors(geConTheaterMovieActors);

        }
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<TheaterList> theaterList(PageQuery pageQuery, HttpServletRequest request) {
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        pageQuery.setPageNum((pageQuery.getPageNum()-1)* pageQuery.getPageSize());
        List<TheaterList> list = geConTheaterMovieMapper.getSeatTimeList(openId);
        list.stream().forEach(item->{
            GeConTheaterPlanMovie geConTheaterPlanMovie = geConTheaterPlanMovieMapper.selectOne(new LambdaQueryWrapper<GeConTheaterPlanMovie>()
                .eq(GeConTheaterPlanMovie::getPlanId,item.getPlanId())
                .orderByDesc(GeConTheaterPlanMovie::getTickets)
                .last("limit 1"));
            if(Objects.nonNull(geConTheaterPlanMovie)){
                GeConTheaterMovie geConTheaterMovie = geConTheaterMovieMapper.selectById(geConTheaterPlanMovie.getMovieId());
                if(Objects.nonNull(geConTheaterMovie)){
                    item.setMovieId(geConTheaterMovie.getId());
                    item.setNewTitle(geConTheaterMovie.getName());
                    item.setNewThumbnail(geConTheaterMovie.getPicture());
                    item.setDuration(geConTheaterMovie.getDuration());
                }
            }
        });
        return new PageInfo<>(list);
    }

    @Transactional
    @Override
    public void cancelTheater(String id, HttpServletRequest request) {
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        GeConTheaterSeat geConTheaterSeat = geConTheaterSeatMapper.selectById(1);
        JSONArray jsonArray = JSONArray.parseArray(geConTheaterSeat.getSeat());
        GeConTheaterSeatTime geConTheaterSeatTime = geConTheaterSeatTimeMapper.selectOne(
                new LambdaQueryWrapper<GeConTheaterSeatTime>()
            .eq(GeConTheaterSeatTime::getOpenId,openId)
            .eq(GeConTheaterSeatTime::getId,id));
        JSONArray jsonArray1 = JSONArray.parseArray(geConTheaterSeatTime.getSeat());
        JSONArray seatList = new JSONArray();
        // 遍历JSONArray中的元素
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject seat = new JSONObject();
            // 获取每个索引对应的元素
            String element = jsonArray.getString(i);
            JSONObject jsonObject = JSONObject.parseObject(element);
            String value = (String)jsonObject.get("value");
            String status = (String)jsonObject.get("status");
            for (int j = 0; j < jsonArray1.size(); j++) {
                String elementJ = jsonArray1.getString(j);
                JSONObject jsonObjectJ = JSONObject.parseObject(elementJ);
                String valueJ = (String)jsonObjectJ.get("value");
                if(Objects.equals(value,valueJ)){
                    status = "0";
                    break;
                }
            }
            seat.put("value",value);
            seat.put("status",status);
            seatList.add(seat);
        }
        geConTheaterSeat.setSeat(seatList.toJSONString());
        geConTheaterSeatMapper.updateById(geConTheaterSeat);
        geConTheaterSeatTimeMapper.deleteById(id);
    }

    @Override
    public CommonResult review(GeConTheaterMovie geConTheaterMovie) {
        boolean flag = false;
        if(4==geConTheaterMovie.getStatus()){//取消发布
            List<GeConTheaterPlanMovie> planMovies = geConTheaterPlanMovieMapper.selectList(new QueryWrapper<GeConTheaterPlanMovie>()
                    .eq("movie_id", geConTheaterMovie.getId())
            );
            for (GeConTheaterPlanMovie planMovie : planMovies) {
                GeConTheaterPlan geConTheaterPlan = geConTheaterPlanMapper.selectById(planMovie.getPlanId());
                if(3==geConTheaterPlan.getStatus()){
                    flag = true;
                    break;
                }
            }
            if(flag){
                return CommonResult.error("有计划正在使用此电影，无法取消发布");
            }
        }
        geConTheaterMovieMapper.updateById(geConTheaterMovie);
        return CommonResult.success("成功");
    }

    @Override
    @Transactional
    public CommonResult add(GeConTheaterMovieDTO geConTheaterMovieDTO) {
        //电影
        GeConTheaterMovie geConTheaterMovie = new GeConTheaterMovie();
        BeanUtils.copyProperties(geConTheaterMovieDTO,geConTheaterMovie);
        geConTheaterMovie.setStatus(4);
        geConTheaterMovie.setIsDelete("0");
        geConTheaterMovieMapper.insert(geConTheaterMovie);

        //演员
        for (GeConTheaterMovieActor actor : geConTheaterMovieDTO.getActors()) {
            GeConTheaterMovieActor geConTheaterMovieActor = new GeConTheaterMovieActor();
            BeanUtils.copyProperties(actor,geConTheaterMovieActor);
            geConTheaterMovieActor.setMovieId(geConTheaterMovie.getId());
            geConTheaterMovieActorMapper.insert(geConTheaterMovieActor);
        }
        return CommonResult.success("添加成功");
    }

    @Override
    public CommonResult edit(GeConTheaterMovieDTO geConTheaterMovieDTO) {
        //电影
        GeConTheaterMovie geConTheaterMovie = new GeConTheaterMovie();
        BeanUtils.copyProperties(geConTheaterMovieDTO,geConTheaterMovie);
        geConTheaterMovieMapper.updateById(geConTheaterMovie);
        //删除原来的演员
        geConTheaterMovieActorMapper.delete(new LambdaQueryWrapper<GeConTheaterMovieActor>()
                .eq(GeConTheaterMovieActor::getMovieId,geConTheaterMovieDTO.getId()));
        //演员
        for (GeConTheaterMovieActor actor : geConTheaterMovieDTO.getActors()) {
            GeConTheaterMovieActor geConTheaterMovieActor = new GeConTheaterMovieActor();
            BeanUtils.copyProperties(actor,geConTheaterMovieActor);
            geConTheaterMovieActor.setMovieId(geConTheaterMovie.getId());
            geConTheaterMovieActorMapper.insert(geConTheaterMovieActor);
        }
        return CommonResult.success("编辑成功");
    }
}
